package com.cskaoyan.day16;

import java.util.Arrays;
import java.util.Comparator;

public class CatTest {
    public static void main(String[] args) {

        Cat[] cats = new Cat[6];
        cats[0] = new Cat(19, "花花MAX", 1000);
        cats[1] = new Cat(15, "咕咕1", 2000);
        cats[2] = new Cat(29, "ZeeZ", 1000);
        cats[3] = new Cat(9, "花花Z", 5000);
        cats[4] = new Cat(12, "大黄-至臻版", 1200);
        cats[5] = new Cat(12, "大黄-至臻版", 100);
        System.out.println("直接实现Comparable接口，按照年龄的从小到大对Cat数组进行自然排序");

        Arrays.sort(cats);
        for (Cat cat : cats) {
            System.out.println(cat);
        }
        System.out.println("-----------------------------------------------------------------------------------");

        Arrays.sort(cats, new Comparator<Cat>() {
            @Override
            public int compare(Cat o1, Cat o2) {
                return (int) (o2.price - o1.price);
            }
        });
        System.out.println(" 匿名内部类，按照price的大到小排序");
        for (Cat cat : cats) {
            System.out.println(cat);
        }

        System.out.println("-----------------------------------------------------------------------------------");
        System.out.println(" lambda分别对Cat数组进行自然排序，name的长短排序，name越长对象越大");
        Arrays.sort(cats, (cat1, cat2) -> cat1.name.length() - cat2.name.length());
        for (Cat cat : cats) {
            System.out.println(cat);
        }
        System.out.println("要求用lambda表达式指向一个方法。age越小对象越小，name越短对象越小，price越大对象越小");
        System.out.println("-----------------------------------------------------------------------------------");
        Arrays.sort(cats, CatTest::method);
        for (Cat cat : cats) {
            System.out.println(cat);
        }

    }

    public static int method(Cat cat1, Cat cat2) {
        if (cat1.age != cat2.age) {
            return cat1.age - cat2.age;
        } else if (cat1.name.length() != cat2.name.length()) {
            return cat1.name.length() - cat2.name.length();
        }
        return (int) (cat2.price - cat1.price);
    }
}

class Cat implements Comparable<Cat> {
    int age;
    String name;
    double price;

    public Cat(int age, String name, double price) {
        this.age = age;
        this.name = name;
        this.price = price;
    }

    @Override
    public int compareTo(Cat o) {
        return age - o.age;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}